﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Models;

namespace Service
{
    public class ModuleManager : IServiceMnanger, IModuleManager
    {
        public IList<ModuleInfo> GetModuleInfo()
        {
            var obj = from o in context.ModuleInfo
                      orderby o.CreateDate descending
                      select o;

            return obj != null ? obj.ToList() : null;
        }

        public ModuleInfo GetModuleInfoByID(int id)
        {
            var obj = from o in context.ModuleInfo
                      where o.ID == id
                      select o;

            return obj != null ? obj.ToList().FirstOrDefault() : null;
        }

        public IList<ModuleInfo> GetModuleInfoByEnity(ModuleInfo parObj)
        {
            var obj = from o in context.ModuleInfo
                      select o;
            if (parObj != null)
            {
                obj = parObj.ID == 0 ? obj : obj.Where<ModuleInfo>(o => o.ID == parObj.ID);
                obj = parObj.PID == null ? obj : obj.Where<ModuleInfo>(o => o.PID == parObj.PID);
                obj = parObj.Code == null ? obj : obj.Where<ModuleInfo>(o => o.Code == parObj.Code);
                obj = parObj.Name == null ? obj : obj.Where<ModuleInfo>(o => o.Name == parObj.Name);
                obj = parObj.Detail == null ? obj : obj.Where<ModuleInfo>(o => o.Detail == parObj.Detail);
                obj = parObj.Sort == null ? obj : obj.Where<ModuleInfo>(o => o.Sort == parObj.Sort);
                obj = parObj.Link == null ? obj : obj.Where<ModuleInfo>(o => o.Link == parObj.Link);
                obj = parObj.CreateBy == null ? obj : obj.Where<ModuleInfo>(o => o.CreateBy == parObj.CreateBy);
                obj = parObj.CreateDate == null ? obj : obj.Where<ModuleInfo>(o => o.CreateDate == parObj.CreateDate);
            }
            return obj != null ? obj.OrderByDescending(o => o.CreateDate).ToList() : null;
        }

        public int DoSaveChanges(ModuleInfo parObj)
        {
            parObj = parObj ?? new ModuleInfo();
            ModuleInfo obj = GetModuleInfoByID(parObj.ID);
            if (obj == null)
            {
                obj = new ModuleInfo();
                context.AddToModuleInfo(obj);
            }

            obj.PID = parObj.PID ?? obj.PID;
            obj.Code = parObj.Code ?? obj.Code;
            obj.Name = parObj.Name ?? obj.Name;
            obj.Detail = parObj.Detail ?? obj.Detail;
            obj.Sort = parObj.Sort ?? obj.Sort;
            obj.Link = parObj.Link ?? obj.Link;
            obj.CreateBy = parObj.CreateBy ?? obj.CreateBy;
            obj.CreateDate = parObj.CreateDate ?? obj.CreateDate ?? DateTime.Now;

            return context.SaveChanges();
        }
    }
}
